package personal.lijun.skeleton.springcloud.serviceprovider.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import personal.lijun.skeleton.springcloud.common.data.ApiResultSet;
import personal.lijun.skeleton.springcloud.utils.validate.DirtyDataException;
import personal.lijun.skeleton.springcloud.utils.validate.ParamValidException;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * @Auther: lijun@sstcsoft.com
 * @Date: 2019/9/10 16:01
 */
@ControllerAdvice
public class GlobalExceptionHanddler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHanddler.class);

    @ExceptionHandler(Throwable.class)
    public  @ResponseBody ApiResultSet handdlerUnknownException(Throwable e){
        logger.error("发生未知错误！",e);
        ApiResultSet apiResultSet = new ApiResultSet();
        apiResultSet.setCode(ApiResultSet.UNKNOWN_ERROR);

        apiResultSet.setMessage("发生未知错误："+e.getMessage());
        StringWriter stringWriter = new StringWriter();
        PrintWriter printWriter = new PrintWriter(stringWriter);
        e.printStackTrace(printWriter);
        String stackTrace = stringWriter.getBuffer().toString();
        apiResultSet.setStackTrace(stackTrace);
        return apiResultSet;
    }

    @ExceptionHandler(ParamValidException.class)
    public  @ResponseBody ApiResultSet handdlerParamValidException(ParamValidException e){
        logger.error("参数验证错误！",e);
        ApiResultSet apiResultSet = new ApiResultSet();
        apiResultSet.setCode(ApiResultSet.PARAM_VALID_ERROR);

        apiResultSet.setMessage("参数验证错误："+e.getMessage());
        return apiResultSet;
    }

    @ExceptionHandler(DirtyDataException.class)
    public @ResponseBody ApiResultSet handleDirtyDataException(DirtyDataException e){
        logger.error("脏数据错误！",e);
        ApiResultSet apiResultSet = new ApiResultSet();
        apiResultSet.setCode(ApiResultSet.DIRTY_DATA_ERROR);

        apiResultSet.setMessage("脏数据错误："+e.getMessage());
        return apiResultSet;
    }
}
